<template>
  <div class="permission-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="permission-tabs">
        <!-- 列表视图 -->
        <el-tab-pane label="列表视图" name="list">
          <!-- 搜索和筛选 -->
          <el-card class="search-card">
            <el-form :model="searchForm" inline>
              <el-form-item label="搜索">
                <el-input
                  v-model="searchForm.search"
                  placeholder="权限名称、代码、描述"
                  clearable
                  @keyup.enter="handleSearch"
                  style="width: 250px;"
                />
              </el-form-item>
              <el-form-item label="模块">
                <el-select v-model="searchForm.module" placeholder="选择模块" clearable style="width: 150px;">
                  <el-option label="用户管理" value="user" />
                  <el-option label="角色管理" value="role" />
                  <el-option label="权限管理" value="permission" />
                  <el-option label="系统管理" value="system" />
                  <el-option label="日志管理" value="log" />
                  <el-option label="后台管理" value="admin" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
                <el-button type="success" @click="handleBatchCreate" v-if="hasPermission(ALL_PERMISSIONS.PERMISSION_CREATE)">
                  <el-icon><Plus /></el-icon>
                  批量创建
                </el-button>
                <el-button type="primary" @click="handleCreate" v-if="hasPermission(ALL_PERMISSIONS.PERMISSION_CREATE)">
                  <el-icon><Plus /></el-icon>
                  创建权限
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 权限列表 -->
          <el-card class="table-card">
            <el-table
              :data="permissionList"
              v-loading="loading"
              stripe
              style="width: 100%"
              :header-cell-style="{ background: '#fafafa', color: '#333' }"
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="权限名称" min-width="150" />
              <el-table-column prop="code" label="权限代码" min-width="180" />
              <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
              <el-table-column prop="module" label="模块" width="120" />
              <el-table-column label="角色数量" width="100" align="center">
                <template #default="{ row }">
                  <el-tag size="small" type="info">{{ row._count?.rolePermissions || 0 }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button size="small" @click="handleEdit(row)" v-if="hasPermission(ALL_PERMISSIONS.PERMISSION_UPDATE)">
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="handleDelete(row)" v-if="hasPermission(ALL_PERMISSIONS.PERMISSION_DELETE)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="pagination.page"
                v-model:page-size="pagination.limit"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 树形视图 -->
        <el-tab-pane label="树形视图" name="tree">
          <el-card>
            <template #header>
              <div class="tree-header">
                <span>权限树形结构</span>
                <el-button @click="fetchPermissionTree" type="primary" size="small">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>
            <el-tree
              :data="permissionTree"
              :props="treeProps"
              node-key="id"
              default-expand-all
              v-loading="treeLoading"
              class="permission-tree"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <span class="node-name">{{ data.name }}</span>
                  <span class="node-code">{{ data.code }}</span>
                  <span class="node-count" v-if="data.roleCount">
                    ({{ data.roleCount }} 角色)
                  </span>
                </div>
              </template>
            </el-tree>
          </el-card>
        </el-tab-pane>

        <!-- 模块视图 -->
        <el-tab-pane label="模块视图" name="module">
          <el-card>
            <template #header>
              <span>按模块分组</span>
            </template>
            <div class="module-grid">
              <div v-for="module in getModulePermissions()" :key="module.module" class="module-card">
                <div class="module-card-header">
                  <h4>{{ module.name }}</h4>
                  <span class="module-count">{{ module.permissions.length }} 个权限</span>
                </div>
                <div class="permission-tags">
                  <el-tag
                    v-for="permission in module.permissions"
                    :key="permission.id"
                    size="small"
                    type="info"
                    class="permission-tag"
                  >
                    {{ permission.name }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 创建/编辑权限对话框 -->
    <el-dialog
      v-model="permissionFormVisible"
      :title="editingPermissionId ? '编辑权限' : '创建权限'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionFormRules"
        label-width="100px"
      >
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="例如: user:list" />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="permissionForm.description" type="textarea" placeholder="请输入权限描述" />
        </el-form-item>
        <el-form-item label="模块" prop="module">
          <el-select v-model="permissionForm.module" placeholder="请选择模块" style="width: 100%;">
            <el-option label="用户管理" value="user" />
            <el-option label="角色管理" value="role" />
            <el-option label="权限管理" value="permission" />
            <el-option label="系统管理" value="system" />
            <el-option label="日志管理" value="log" />
            <el-option label="后台管理" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作" prop="action">
          <el-select v-model="permissionForm.action" placeholder="请选择操作" style="width: 100%;">
            <el-option label="列表" value="list" />
            <el-option label="查看" value="read" />
            <el-option label="创建" value="create" />
            <el-option label="更新" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="启用" value="enable" />
            <el-option label="禁用" value="disable" />
            <el-option label="重置" value="reset" />
            <el-option label="导出" value="export" />
            <el-option label="导入" value="import" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源" prop="resource">
          <el-select v-model="permissionForm.resource" placeholder="请选择资源" style="width: 100%;">
            <el-option label="用户" value="user" />
            <el-option label="角色" value="role" />
            <el-option label="权限" value="permission" />
            <el-option label="配置" value="config" />
            <el-option label="统计" value="stats" />
            <el-option label="日志" value="log" />
            <el-option label="系统" value="system" />
            <el-option label="后台" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="permissionFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量创建对话框 -->
    <el-dialog
      v-model="batchFormVisible"
      title="批量创建权限"
      width="800px"
      destroy-on-close
    >
      <el-form :model="batchForm" label-width="100px">
        <el-form-item label="资源">
          <el-select v-model="batchForm.resource" placeholder="请选择资源" style="width: 100%;">
            <el-option label="用户" value="user" />
            <el-option label="角色" value="role" />
            <el-option label="权限" value="permission" />
            <el-option label="配置" value="config" />
            <el-option label="统计" value="stats" />
            <el-option label="日志" value="log" />
            <el-option label="系统" value="system" />
            <el-option label="后台" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作">
          <el-checkbox-group v-model="batchForm.actions">
            <el-checkbox label="list">列表</el-checkbox>
            <el-checkbox label="read">查看</el-checkbox>
            <el-checkbox label="create">创建</el-checkbox>
            <el-checkbox label="update">更新</el-checkbox>
            <el-checkbox label="delete">删除</el-checkbox>
            <el-checkbox label="enable">启用</el-checkbox>
            <el-checkbox label="disable">禁用</el-checkbox>
            <el-checkbox label="reset">重置</el-checkbox>
            <el-checkbox label="export">导出</el-checkbox>
            <el-checkbox label="import">导入</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="模块">
          <el-input v-model="batchForm.module" placeholder="请输入模块名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { permissionApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { Permission } from '@/types'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import { formatDate } from '@/utils/format'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const treeLoading = ref(false)
const permissionList = ref<Permission[]>([])
const permissionTree = ref([])
const permissionFormVisible = ref(false)
const batchFormVisible = ref(false)
const editingPermissionId = ref<number | null>(null)
const activeTab = ref('list')

// 搜索表单
const searchForm = reactive({
  search: '',
  module: ''
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 权限表单
const permissionForm = reactive({
  code: '',
  name: '',
  description: '',
  module: '',
  action: '',
  resource: ''
})

// 批量创建表单
const batchForm = reactive({
  resource: '',
  actions: [] as string[],
  module: ''
})

// 表单验证规则
const permissionFormRules = {
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  module: [
    { required: true, message: '请选择模块', trigger: 'change' }
  ]
}

// 树形结构配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 权限检查
const hasPermission = (permission: string) => {
  return userStore.hasPermission(permission)
}

// 获取权限列表
const fetchPermissions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    const response = await permissionApi.getPermissions(params)
    permissionList.value = response.data.data
    pagination.total = response.data.pagination.total
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限树形结构
const fetchPermissionTree = async () => {
  treeLoading.value = true
  try {
    const response = await permissionApi.getTree()
    const treeData = response.data.tree.map((module: any) => ({
      id: module.module,
      name: module.name,
      children: module.permissions.map((permission: any) => ({
        id: permission.id,
        name: permission.name,
        code: permission.code,
        description: permission.description,
        action: permission.code.split(':')[1] || permission.code,
        resource: permission.code.split(':')[0] || permission.code,
        roleCount: permission.roleCount
      }))
    }))
    permissionTree.value = treeData
  } catch (error) {
    ElMessage.error('获取权限树形结构失败')
  } finally {
    treeLoading.value = false
  }
}

// 获取权限模块
const fetchPermissionModules = async () => {
  try {
    const response = await permissionApi.getModules()
    // 可以用于模块选择
  } catch (error) {
    ElMessage.error('获取权限模块失败')
  }
}

// 获取模块权限
const getModulePermissions = (moduleName?: string) => {
  if (moduleName) {
    return permissionList.value.filter(p => p.module === moduleName)
  }
  // 返回所有模块分组
  const modules = new Map()
  permissionList.value.forEach(permission => {
    if (!modules.has(permission.module)) {
      modules.set(permission.module, {
        module: permission.module,
        name: permission.module,
        permissions: []
      })
    }
    modules.get(permission.module).permissions.push(permission)
  })
  return Array.from(modules.values())
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchPermissions()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    module: ''
  })
  pagination.page = 1
  fetchPermissions()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchPermissions()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchPermissions()
}

// 创建权限
const handleCreate = () => {
  editingPermissionId.value = null
  Object.assign(permissionForm, {
    code: '',
    name: '',
    description: '',
    module: '',
    action: '',
    resource: ''
  })
  permissionFormVisible.value = true
}

// 编辑权限
const handleEdit = (row: Permission) => {
  editingPermissionId.value = row.id
  loadPermissionData(row)
  permissionFormVisible.value = true
}

// 删除权限
const handleDelete = async (row: Permission) => {
  try {
    await ElMessageBox.confirm(`确定要删除权限 "${row.name}" 吗？`, '确认删除', {
      type: 'warning'
    })
    await permissionApi.deletePermission(row.id)
    ElMessage.success('权限删除成功')
    fetchPermissions()
    fetchPermissionTree()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('权限删除失败')
    }
  }
}

// 批量创建
const handleBatchCreate = () => {
  Object.assign(batchForm, {
    resource: '',
    actions: [],
    module: ''
  })
  batchFormVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (editingPermissionId.value) {
      await permissionApi.updatePermission(editingPermissionId.value, permissionForm)
      ElMessage.success('权限更新成功')
    } else {
      await permissionApi.createPermission(permissionForm)
      ElMessage.success('权限创建成功')
    }
    permissionFormVisible.value = false
    fetchPermissions()
    fetchPermissionTree()
  } catch (error) {
    ElMessage.error(editingPermissionId.value ? '权限更新失败' : '权限创建失败')
  }
}

// 批量提交
const handleBatchSubmit = async () => {
  try {
    const permissions = batchForm.actions.map(action => ({
      code: `${batchForm.resource}:${action}`,
      name: `${batchForm.resource} ${action}`,
      description: `${batchForm.resource} ${action} 权限`,
      module: batchForm.module || batchForm.resource
    }))
    
    await permissionApi.batchCreate(permissions)
    ElMessage.success('批量创建权限成功')
    batchFormVisible.value = false
    fetchPermissions()
    fetchPermissionTree()
  } catch (error) {
    ElMessage.error('批量创建权限失败')
  }
}

// 重置权限表单
const resetPermissionForm = () => {
  Object.assign(permissionForm, {
    code: '',
    name: '',
    description: '',
    module: '',
    action: '',
    resource: ''
  })
}

// 加载权限数据
const loadPermissionData = (permission: Permission) => {
  const codeParts = permission.code.split(':')
  const resource = codeParts[0] || ''
  const action = codeParts[1] || ''
  
  Object.assign(permissionForm, {
    code: permission.code,
    name: permission.name,
    description: permission.description || '',
    module: permission.module || resource,
    action: action,
    resource: resource
  })
}

// 监听代码变化，自动生成名称
const watchCodeChange = () => {
  if (permissionForm.code) {
    permissionForm.resource = getResourceFromCode(permissionForm.code)
    permissionForm.action = getActionFromCode(permissionForm.code)
    if (!permissionForm.module) {
      permissionForm.module = permissionForm.resource
    }
  }
}

// 从代码中提取资源
const getResourceFromCode = (code: string) => {
  const parts = code.split(':')
  return parts[0] || ''
}

// 从代码中提取操作
const getActionFromCode = (code: string) => {
  const parts = code.split(':')
  return parts[1] || ''
}

// 初始化
onMounted(() => {
  fetchPermissionTree()
  fetchPermissions()
  fetchPermissionModules()
})
</script>

<style scoped>
.permission-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-card .el-form {
  margin: 0;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

/* 标签页样式 */
.permission-tabs {
  margin-top: 20px;
}

/* 表格样式 */
.el-table {
  margin-bottom: 20px;
}

.el-table th {
  background: #fafafa;
  font-weight: 600;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  padding: 16px 0;
}

/* 树形视图样式 */
.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-tree {
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 4px 0;
}

.node-name {
  font-weight: 600;
  color: #333;
}

.node-code {
  color: #666;
  font-size: 12px;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.node-count {
  color: #999;
  font-size: 12px;
  background: #e6f7ff;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 模块视图样式 */
.module-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.module-card {
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #eee;
  transition: all 0.3s ease;
}

.module-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.module-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.module-card-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.module-count {
  color: #666;
  font-size: 12px;
  background: #e6f7ff;
  padding: 4px 8px;
  border-radius: 4px;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  margin: 0;
  border-radius: 4px;
  font-size: 12px;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  padding: 24px 24px 0 24px;
  border-bottom: 1px solid #eee;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px 24px 24px;
  border-top: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .permission-list {
    padding: 16px;
  }
  
  .search-card .el-form {
    flex-direction: column;
  }
  
  .search-card .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .module-grid {
    grid-template-columns: 1fr;
  }
  
  .tree-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style> 